﻿using Autofac;
using System.Linq;
using System.Reflection;
using Loong.Dependency;

namespace Loong.Events.Bus.Handlers
{
    public static class EventHandlerRegister
    {
        public static void Register(Assembly assembly)
        {
            var eventBus = IocManager.IocContainer.Resolve<IEventBus>();

            var eventHandlerType = typeof(IAsyncEventHandler<>);
            var handlerTypes = assembly.GetTypes().Where(type => !type.IsInterface && type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == eventHandlerType));
            foreach (var handlerType in handlerTypes)
            {
                var handlerInterface = handlerType.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == eventHandlerType).First();
                var eventType = handlerInterface.GetGenericArguments().First();

                eventBus.Register(eventType, handlerType);
            }
        }
    }
}
